// import Vue from 'vue'
import axios from 'axios'
import store from '../store'
export const API_PRE = '/api/'
export const API_SUFFIX = '.vdt'

const service = axios.create({
  // timeout: 5000
})

// request拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers['token'] = store.getters.token // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

service.interceptors.response.use(
  response => {
    let status = response.status
    let data = response.data
    try {
      if (typeof data === 'string') {
        data = JSON.parse(data)
      }
    } catch (e) {}
    let options = {}
    if (status === 401) {
      window.location.href = '/login'
      /*
       * @desc: 注销后跳转.下述代码在客户正式的环境上需要加上. 同时注释上述跳转到登录页代码
      */
      let url = 'http://sso.chinagasholdings.com:8080/sso/logout?service=http://myhr.chinagasholdings.com'
      window.open(url, '_self')
    } else if (status === 500) {
      // Notice.error({
      //   title: response.statusText,
      //   desc: response.data,
      //   duration: 0
      // })
    } else if (status === 200) {
      if (response.data['<isError>']) {
        options.title = ''
        options.desc = data.message
        Message.error(options)
      } else if (data.data && data.data['ecode'] === '401') {
        options.desc = data.data['msg'] || 'Timeout'
        options.duration = 3
        options.key = 'timeout-error'
        store.dispatch('browserLogout')
        Message.error(options)
        window.location.href = '/login'
        /*
         * @desc: 注销后跳转. 下述代码在客户正式的环境上需要加上.跳转到验证界面, 同时注释上述跳转到登录页代码
        */
        let url = 'http://sso.chinagasholdings.com:8080/sso/logout?service=http://myhr.chinagasholdings.com'
        window.open(url, '_self')
      }
    }
    return response
  },
  error => {
    console.log('err' + error)// for debug
    Message.error({
      desc: error.message,
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export const getApiJson = (url, args = {}, _ignoreError) => {
  const promise = new Promise((resolve, reject) => {
    // Vue.http.get(url, args)
    service.get(url, {
      params: args
    })
    .then((res) => {
      if (res.data.success) {
        resolve(res.data.data)
      } else {
        console.error(res)
        if (!_ignoreError) {
          // Message.error(res.data && res.data.data  && res.data.data.msg || 'error');
          Notice.error({
            title: '错误',
            desc: res.data && res.data.data && res.data.data.msg,
            duration: 0
          })
        }
        reject(res.data && res.data.data)
      }
    })
    .catch((err) => {
      reject(err)
    })
  })
  return promise
}

export const invoke = function (url, args, params = {}, ignoreError) {
  // let argsStr = JSON.stringify({args: args})
  let _params
  let _ignoreError = false
  for (let i = 2; i < arguments.length; i++) {
    const _arg = arguments[i]
    if (typeof _arg === 'boolean') {
      _ignoreError = _arg
    } else if (typeof _arg === 'object') {
      _params = _arg
    }
  }
  url = _.trim(url)
  if (!/.vdt$/.test(url) && !/.vdp$/.test(url)) {
    url += API_SUFFIX
  }
  if (!/^\/?api\//i.test(url)) {
    url = API_PRE + url
  }
  // debugger
  let promise = new Promise((resolve, reject) => {
    service({
      url: url,
      method: 'post',
      // data: JSON.stringify(_.extend({args: args}, _params))
      data: _.extend({args: args}, _params)
    }).then((res) => {
      if (res.data.success) {
        resolve(res.data.data)
      } else {
        // debugger
        console.error(res)
        if (!_ignoreError) {
          // Message.error(res.data && res.data.data  && res.data.data.msg || 'error');
          Notice.error({
            title: '错误',
            desc: res.data && res.data.data && res.data.data.msg,
            duration: 0
          })
        }
        reject(res.data && res.data.data)
      }
    }).catch((err) => {
      reject(err)
    })
  })
  return promise
}

// export default service
